package com.jichangxiu.framework.aspect;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.jichangxiu.common.annotation.Scope;
import com.jichangxiu.common.constant.Constants;
import com.jichangxiu.common.context.JcxContext;
import com.jichangxiu.common.entity.dto.QueryEntity;
import com.jichangxiu.common.entity.po.BaseEntity;
import com.jichangxiu.framework.utils.ScopeUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Slf4j
@Aspect
@Component
public class ScopeAspect {

    @Before("@annotation(scope)")
    public void doBefore(JoinPoint joinPoint, Scope scope) {
        clearScope(joinPoint);
        handleScope(joinPoint, scope);
    }

    private void clearScope(final JoinPoint joinPoint) {
        // 拼接权限 sql 前先清空 params dataScope 参数防止注入
        Object params = joinPoint.getArgs()[0];
        if (ObjectUtil.isNotEmpty(params) && params instanceof BaseEntity) {
            BaseEntity entity = (BaseEntity) params;
            entity.getParams().put(Constants.AND_DATA_SCOPE, "");
            entity.getParams().put(Constants.DATA_SCOPE, "");
        }
        if (ObjectUtil.isNotEmpty(params) && params instanceof QueryEntity) {
            QueryEntity entity = (QueryEntity) params;
            entity.getParams().put(Constants.AND_DATA_SCOPE, "");
            entity.getParams().put(Constants.DATA_SCOPE, "");
        }
    }

    protected void handleScope(final JoinPoint joinPoint, Scope scope) {
        // 获取当前的用户
        // 如果获取不到有效用户，就不进行权限 sql 拼接
        // 如果是租户超级管理员和平台超级管理员，就不进行权限 sql 拼接
        if (ObjectUtil.isNotEmpty(JcxContext.getJti()) && !Constants.TEN_SUPER_USER.equals(JcxContext.getUserCode()) && !Constants.SYS_SUPER_USER.equals(JcxContext.getUserCode())) {
            scopeFilter(joinPoint, scope);
        }
    }

    public static void scopeFilter(JoinPoint joinPoint, Scope scope) {
        String dataScope = ScopeUtils.getDataScope(scope);
        if (StrUtil.isNotEmpty(dataScope)) {
            Object params = joinPoint.getArgs()[0];
            if (ObjectUtil.isNotEmpty(params) && params instanceof BaseEntity) {
                BaseEntity entity = (BaseEntity) params;
                entity.getParams().put(Constants.AND_DATA_SCOPE, " AND (" + dataScope + ")");
                entity.getParams().put(Constants.DATA_SCOPE, dataScope);
            }
            if (ObjectUtil.isNotEmpty(params) && params instanceof QueryEntity) {
                QueryEntity queryEntity = (QueryEntity) params;
                queryEntity.getParams().put(Constants.AND_DATA_SCOPE, " AND (" + dataScope + ")");
                queryEntity.getParams().put(Constants.DATA_SCOPE, dataScope);
            }
        }
    }

}
